package com.duck.inspection.service;

import cn.hutool.extra.tokenizer.engine.analysis.AnalysisResult;
import com.duck.inspection.domain.po.DuckMetricsPojo;
import com.duck.inspection.enums.DuckAgeStage;
import com.duck.inspection.utils.QianWenChat;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AIService {
    private static final Logger logger = LoggerFactory.getLogger(AIService.class);

    // 增强版Prompt模板
    private static final String ENHANCED_PROMPT = """
        作为家禽健康分析专家，请严格按以下要求分析%d只%s鸭群数据：

        原始数据：
        %s

        分析要求：
        1. 健康评分（0-10分）：需说明评分依据
        2. 异常检测：检查以下指标是否达标
           - 体重、胫长、龙骨长度、胸深、胸宽
           - 参考标准：%s阶段标准值
           异常检测要求：
                   - 必须明确标注metric字段（体重/胫长/龙骨长度等）
                   - 使用中文指标名称
        3. 改善建议需包含：
           - 营养管理（至少2条）
           - 疾病预防（至少1条）
           - 环境调控（至少1条）
           - 生长监测（至少1条）
        4. 总结分析：
           - 群体优势（至少1项）
           - 主要风险（至少2项）
           - 优先行动（至少3项）

        返回严格JSON格式（不要任何注释和markdown）：
        {
            "score": 健康评分分数,
            "scoreReason": ["扣分原因1", "扣分原因2"],
            "abnormalDucks": [{
                "id": 3,
                "metric": "体重",
                "value": 0.75,
                "unit": "kg",
                "standardRange": [0.78, 0.85]
            }],
            "suggestions": {
                "nutrition": ["建议1", "建议2"],
                "disease": ["建议3"],
                "environment": ["建议4"],
                "monitoring": ["建议5"]
            },
            "summary": {
                "strengths": ["群体优势1"],
                "risks": ["风险1", "风险2"],
                "priorityActions": ["行动1", "行动2", "行动3"]
            }
        }
        """;

    @Data
    public static class AnalysisResult {
        private String summary;
        private Double healthScore;
        private List<String> scoreReasons = new ArrayList<>();
        private List<AbnormalDuck> abnormalDucks = new ArrayList<>();
        private Map<String, List<String>> categorizedSuggestions = new HashMap<>();
        private SummaryAnalysis summaryAnalysis;
    }

    @Data
    public static class SummaryAnalysis {
        private List<String> strengths;
        private List<String> risks;
        private List<String> priorityActions;
    }

    @Data
    public static class AbnormalDuck {
        private Integer duckId;
        private String metric;
        private Double value;
        private String unit;
        private Double[] standardRange;
    }

    public AnalysisResult analyze(List<DuckMetricsPojo> ducks) {
        try {
            DuckAgeStage stage = DuckAgeStage.fromCode(ducks.get(0).getAgeStageCode());
            String dataDesc = buildEnhancedDataDesc(ducks);
            String standards = loadStageStandards(stage);

            String prompt = String.format(ENHANCED_PROMPT,
                    ducks.size(),
                    stage.getDisplayName(),
                    dataDesc,
                    standards
            );

            logger.debug("Sending AI prompt: {}", prompt);
            String response = QianWenChat.callWithMessage(prompt);
            logger.debug("Raw AI response: {}", response);

            return parseEnhancedResponse(response);
        } catch (Exception e) {
            logger.error("Analysis failed", e);
            return buildFallbackResult(ducks);
        }
    }

    private String buildEnhancedDataDesc(List<DuckMetricsPojo> ducks) {
        return ducks.stream()
                .map(d -> String.format("编号%d：体重%.2fkg | 胫长%.1fcm | 龙骨%.1fcm | 胸深%.1fcm | 胸宽%.1fcm",
                        d.getId(), d.getWeight(), d.getTibiaLength(),
                        d.getKeelLength(), d.getChestDepth(), d.getChestWidth()))
                .collect(Collectors.joining("\n"));
    }

    private AnalysisResult parseEnhancedResponse(String response) throws AnalysisException {
        try {
            // 只去除 ``` 标记，其余保留所有字符（包括中文）
            String cleanedJson = response.replaceAll("(?i)```(json)?", "").trim();

            ObjectMapper mapper = new ObjectMapper();
            JsonNode root = mapper.readTree(cleanedJson);

            AnalysisResult result = new AnalysisResult();

            // 解析评分
            if (root.has("score")) {
                result.setHealthScore(root.get("score").asDouble());
                if (root.has("scoreReason")) {
                    root.get("scoreReason").forEach(n ->
                            result.getScoreReasons().add(n.asText()));
                }
            }

            // 解析异常个体
            if (root.has("abnormalDucks")) {
                for (JsonNode node : root.get("abnormalDucks")) {
                    AbnormalDuck duck = new AbnormalDuck();
                    duck.setDuckId(node.get("id").asInt());
                    duck.setMetric(node.get("metric").asText());
                    duck.setValue(node.get("value").asDouble());
                    duck.setUnit(node.get("unit").asText());
                    JsonNode range = node.get("standardRange");
                    duck.setStandardRange(new Double[]{
                            range.get(0).asDouble(),
                            range.get(1).asDouble()
                    });
                    result.getAbnormalDucks().add(duck);
                }
            }

            // 解析建议
            if (root.has("suggestions")) {
                JsonNode sugg = root.get("suggestions");
                result.getCategorizedSuggestions().put("nutrition", parseList(sugg, "nutrition"));
                result.getCategorizedSuggestions().put("disease", parseList(sugg, "disease"));
                result.getCategorizedSuggestions().put("environment", parseList(sugg, "environment"));
                result.getCategorizedSuggestions().put("monitoring", parseList(sugg, "monitoring"));
            }

            // 解析总结分析
            SummaryAnalysis summary = new SummaryAnalysis();
            if (root.has("summary")) {
                JsonNode sumNode = root.get("summary");
                summary.setStrengths(parseList(sumNode, "strengths"));
                summary.setRisks(parseList(sumNode, "risks"));
                summary.setPriorityActions(parseList(sumNode, "priorityActions"));
            } else {
                summary.setStrengths(List.of("未提供优势分析"));
                summary.setRisks(List.of("未提供风险分析"));
                summary.setPriorityActions(List.of("请检查数据完整性"));
            }
            result.setSummaryAnalysis(summary);

            return result;
        } catch (IOException e) {
            throw new AnalysisException("Failed to parse AI response: " + e.getMessage(), e);
        }
    }


    private List<String> parseList(JsonNode node, String field) {
        List<String> list = new ArrayList<>();
        if (node.has(field)) {
            node.get(field).forEach(n -> list.add(n.asText()));
        }
        return list;
    }

    private String loadStageStandards(DuckAgeStage stage) {
        return stage.getStandardDesc();
    }

    private AnalysisResult buildFallbackResult(List<DuckMetricsPojo> ducks) {
        AnalysisResult result = new AnalysisResult();
        result.setHealthScore(7.0);
        result.setScoreReasons(List.of("分析服务暂时不可用"));

        SummaryAnalysis summary = new SummaryAnalysis();
        summary.setStrengths(List.of("系统维护中"));
        summary.setRisks(List.of("请检查网络连接"));
        summary.setPriorityActions(List.of("稍后重试"));
        result.setSummaryAnalysis(summary);

        return result;
    }

    public static class AnalysisException extends RuntimeException {
        public AnalysisException(String message, Throwable cause) {
            super(message, cause);
        }
    }
}